package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.Product;
import com.guyan.form.ProductForm;
import com.guyan.service.ProductService;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * ClassName： ProductController
 * Date： 2021/5/24 15:37
 *
 * @author 孤焰
 * @version 1.0
 **/

@Controller
@RequestMapping("/product")
@ResponseBody
public class ProductController {

    @Autowired
    ProductService productService;

    @GetMapping("/productList")
    public LayuiVo productList(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer limit,
                               Integer categoryId,
                               String search) {
        // TODO search变量中文在前端控制台显示乱码
        PageInfo pageInfo = productService.productList(page, limit, categoryId, search);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @PostMapping("/updateProductById")
    public ResultVo updateProductById(@RequestBody Product product) {
        return productService.updateProductById(product);
    }

    @PostMapping("/addProduct")
    public ResultVo addProduct(@RequestBody @Valid ProductForm productForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Product product = new Product();
        BeanUtils.copyProperties(productForm, product);

        return productService.addProduct(product);
    }

    @PostMapping("/batchDelProduct")
    public ResultVo batchDelProduct(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultVo.error(5001, "未选择要删除的产品");
        }

        return productService.batchDelProduct(ids);
    }
}
